<template>
    <div class="book-for-student">
        <div class="addBook">
            <el-button type="primary" @click="showAddForm = true">添加书籍<i
                    class="el-icon-upload el-icon--right"></i></el-button>
            <el-form :inline="true" class="search-form">
                <el-form-item label="" style="width: 150px; display: flex;">
                    <el-input v-model="searchBook" placeholder="请输入书籍名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">搜索</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="book1-for-student">
            <el-table :data="tableData" style="width: 100%" :expand-row-keys="expandRowKeys"
                @expand-change="handleRowExpand" :row-key="bookKey">
                <el-table-column type="expand">
                    <template slot-scope="props">
                        <el-form label-position="left" inline class="demo-table-expand">
                            <el-form-item label="书籍名称">
                                <span>{{ props.row.name }}</span>
                            </el-form-item>
                            <el-form-item label="作者">
                                <span>{{ props.row.author }}</span>
                            </el-form-item>
                            <el-form-item label="书籍Id">
                                <span>{{ props.row.id }}</span>
                            </el-form-item>
                            <el-form-item label="书籍描述">
                                <span>{{ props.row.description }}</span>
                            </el-form-item>
                            <el-form-item label="书籍类型">
                                <span>{{ props.row.category }}</span>
                            </el-form-item>
                            <el-form-item label="剩余书籍">
                                <span>{{ props.row.remain }}</span>
                            </el-form-item>
                            <el-form-item label="图片">
                                <img :src="props.row.url" alt="" style="width: 150px; height: 150px;">
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column label="书籍 ID" prop="id" width="200">
                </el-table-column>
                <el-table-column label="书籍名称" prop="name" width="200">
                </el-table-column>
                <el-table-column label="书籍描述" prop="description" width="1200">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="props">
                        <el-button type="danger" icon="el-icon-delete" circle @click="del(props.row.id)"> </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div>
            <el-dialog title="添加书籍" :visible.sync="showAddForm">
                <el-form :model="newBook">
                    <el-form-item label="书籍名称" :label-width="formLabelWidth">
                        <el-input v-model="newBook.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="书籍描述" :label-width="formLabelWidth">
                        <el-input v-model="newBook.description" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="书籍作者" :label-width="formLabelWidth">
                        <el-input v-model="newBook.author" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="书籍分类" :label-width="formLabelWidth">
                        <el-input v-model="newBook.category" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="书籍图片" :label-width="formLabelWidth">
                        <el-input v-model="newBook.url" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="showAddForm = false" class="cancel-btn">取 消</el-button>
                    <el-button type="primary" @click="addBook">确 定</el-button>
                </div>
            </el-dialog>
        </div>
        <div class="block" style="display: flex;justify-content:center;padding: 20px 20px 0 0 ;margin-top: 30px;">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[7]"
                :page-size="pageSize" :current-page="currentPage" layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
    </div>
</template>

<script>
import axios from 'axios';


export default {
    data() {
        return {
            total: 0,
            currentPage: 1,
            pageSize: 7,
            expandRowKeys:[],
            tableData: [],
            studentList:[],
            showChangeFrom: false,
            name:'',
            formLabelWidth: '120px',
            studentNames:[],
            Selectbook: null,
            showAddForm:false,
            newBook:{
                name:'',
                id:'',
                description:'',
                author:'',
                category:'',
                url:'',
                remain:''
            },
            searchBook: ''
        }
    },
    methods: {
        handleSizeChange(val) {
            this.pageSize = val;
            this.fetchData();
            this.currentPage = 1;
            console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.fetchData();
            console.log(`当前页: ${val}`);
        },
        // getImage(id){
        //     console.log(`http://localhost:8081/book/image/${id}`)
        //     return `http://localhost:8081/book/image/${id}`
        // },
        openChangeForm(book){
            this.Selectbook = book;
            this.showChangeFrom = true;
        },
        update() {
            if(this.studentNames.includes(this.name)){
                if(!this.Selectbook.student.includes(this.name) || this.Selectbook.student.length==0){
                    this.Selectbook.student = this.Selectbook.student.concat(" " + this.name);
                    axios.put(`/book/${this.Selectbook.id}`, this.Selectbook).then(res => {
                        this.tableData = this.tableData.map(item => (item.id === this.Selectbook.id ? res.data : item));
                        alert('添加成功');
                        this.name ='',
                        this.showChangeFrom = false;
                    })
                }else{
                    alert("该学生已添加")
                }
            }else{
                alert("该学生不存在，请重新输入")
            }
            
            this.name ='',
            this.showChangeFrom = false;
        },
        addBook(){
            const newBook = {...this.newBook}
            axios.post('/book', newBook).then(res => {
                const newBook = res.data
                this.tableData.push(newBook)
                this.showAddForm = false
                this.newBook = {
                    name: '',
                    description: '',
                    author: '',
                    category: '',
                    url: '',
                }
                alert('添加成功')
            })
        },
        del(id) {
            axios.delete(`/book/${id}`).then(res => {
                this.tableData = this.tableData.filter(item => item.id !== id)
                alert('删除成功')
            })
        },
        search() {
            if (this.searchBook.trim() !== '') {
                axios.get(`/book/search/${encodeURIComponent(this.searchBook.trim())}`).then(res => {
                    const searchResults = res.data;

                    // 更新 tableData 为搜索结果
                    this.tableData = searchResults;

                    if (searchResults.length === 0) {
                        alert('没有找到匹配的书籍');
                    }
                    this.searchBook = '';
                }).catch(err => {
                    console.error('搜索失败:', err);
                    alert('搜索过程中发生错误');
                });
            } else {
                // 如果没有输入查询字符串，则显示所有书籍
                axios.get("/book").then(res => {
                    this.tableData = res.data;
                }).catch(err => {
                    console.error('获取书籍失败:', err);
                    alert('获取书籍列表时发生错误');
                });
            }
        },
        handleRowExpand(row, expandedRows){
            if (expandedRows.length > 0) {
                this.expandRowKeys = [row.id];
            } else {
                this.expandRowKeys = [];
            }
        },
        bookKey(row){
            return row.id
        },
        fetchData() {
            axios.get('/books', {
                params: {
                    page: this.currentPage,
                    pageSize: this.pageSize
                }
            }).then(response => {
                const data = response.data;
                console.log(data)
                if (data && Array.isArray(data.items)) {
                    this.tableData = data.items; // 更新表格显示的数据
                    this.total = data.total;     // 更新总记录数
                } else {
                    console.error('Unexpected response format from server:', data);
                }
            }).catch(error => {
                console.error('Error fetching data:', error);
                // 可选：向用户显示错误信息
                alert('加载数据失败，请稍后再试');
            });
        },
    },
    
    created() {
        this.fetchData();
        // axios.get("/book").then(res => {
        //     this.tableData = res.data
        //     console.log(this.tableData);
        // })
        axios.get("/user").then(res => {
            this.studentList = res.data
            console.log(this.studentList);
            this.studentNames = this.studentList.map(item => item.name);
            console.log(this.studentNames);
        })
    },

}
</script>

<style>
.demo-table-expand {
    font-size: 0;
}

.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}

.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
}
.addBook{
    display: flex;
    position: relative;
    top: 5px;
    padding-top: 10px;
    height: 50px;
    width: 100px;
}
.search-form{
    position: absolute;
    height: 50px;
    left: 1300px;
    top: 20px;
    display: flex;
}
.book1-for-student{
    margin-top: 30px;
}
</style>